package com.bishe.o2oo.util.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

public class AliPayUtil {
    private final static Logger LOG = LoggerFactory.getLogger(AliPayUtil.class);

    private final static String APP_ID = "2016080300159983";
    private final static String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDnptSr0NJHXOeOBGs0LanzO6+0MsbvrhQWMG+beDCol8KbiASr0jiGMZg3TacgTjng5VNobg1sOtxRjMbrl9Is4I/QhkpUyi+JZCs8iuLZCaqloMtuYb2GXYv3TAVkfi1h5BRRRbnaIpg3d+Jv78wdBQ0UJ0NNT5CX0JFdjNBDcwdl5zeS6Al0Byc2Ibmd6Jw+cBZZZm4VKKyVwsCbUGzaV6+J7bO7k1y7c7d6xZV3xBWaj+nfaEm9MPqMM27TMSKcMUU92zJ+8Llac7dHL1wiv69N6c/a6IV5ju/9aWRjk8m1eQbsT71AUFt/0qSgEv95ZuemDo4odOPTjWMYAFhxAgMBAAECggEATulY5xKinya5xnog3sxzaWU6rGLju8AMHabwTgC6aqQP6hWCqdlZ4fTBCo3MUcf0FXVpXVin/+dpJ+qR1K2KLjltJDaq2Ylqeh4CUIRrVE3jsLo+smJfQodZZ6ug5qPI5+DfPvRGpFVGjxaqr0D7wiL3WpcpaQuikOS+sCSIyYCe2035iJFBx8s1MCnLCCi4BazcrgBDZmT+jxaKEUufOPRTcGH4uKqIPVQZpkv91YYj0oourV5ec8nVXY37eRxXwA38NsyeHWk0rve2MknA9bZIbPtQTdrj9xEXkS4W2utWwi7H8kZwuHf8hThubfwlCUYSr8HYiKGxVR5nUpZYBQKBgQD5/x22qwgSxAj19qSuq+jaAvAlYGfXg6qG5s60OhsqaIalsxPOLspPRWxG9KcxaUZR5BfUfGNLmJCnuEWaH+oGTxYq0AzgA8PuUDYXXnTGU9pWltrKW0fRFZwLVLvwoo0hRcJyQZ9DDUHcGBhy6nsXt/VZ1L3t5RluAdy18THeqwKBgQDtNu/6INhbZrgbQvaRQifv1+712/AW3VqK9W2bnY/vMwRk+2cz8Ti6/gMMRm9wF0xWgUv0x6cu/ZP13Fd/phTXSddACBWdAS+LSwwnfpdYKAx7UcBDWXO12ONk4R80PQcNMMybd00saJlom0KqopvlQzPW11oYKu4WttlYOjN1UwKBgBSExuiOQxxfMKkXdE7N10/Fe/ZlYkCDEwT9fqu2NTKW365L820x0/MLrKZqQCrDDD1+biJHj1LOE9lgO3457lhUN2qOJvBf/r3ZoYbrfsQkb8A5o32GXm+fyW34p3BJtzGq6xm7nxm+xdANvjv4WOAKfj3AQ1J6QksQJhBc2o3/AoGBAIaUHW+9xKGOVDL7OaHNc5Tp3+NSRRLjwCOH/AhGSst9GSglTTa1yuajh50mNMDWJvQI5MvZnWrWaGQa/vUnhzlg5iKos4JgktWm3R1m/3v/NJ2eEsLi8/eeNdwcsDRVzzNXlS06cOkZ6rbjJt5h5KocB0QC51VAvdTbJdGdK2aLAoGBAOcmfj8RuGw6cGFGfvQuBfODBop7WR1hZLdraQ/v/T60dNoG5FWxyVvENn9lwpIxg6HYDY3VoQRjXXtW+hKPLChdUmxoaDSSV7BKwHEX9TJkxGBmKn1o/sT/dV7o1lUV5Gq1uiV3ZLwpF8ipoGsNsZc15Oi9g6Lc+goU/S1RX/33";
    public final static String CHARSET = "UTF-8";
    private final static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAln4KZNhqXMHy/uzzFc0fCAD9KloKk8FbH4IS7P8sRHfYQ8sIQVSv1ZDZsTns74thFd5AhUcR03bFasqs0dH0Jmn5jJ1kvu/7ojAsbbO5+coLaWLqTlRuzL8k1OhCn6Hu6OYr23WlIjHJc45XrYRnbQ7ifsB5T9m3RL+o7p3yqdwNBnsCpqKFJc4GVGh40AXS2Oqb5uinMeL58GLXCQCFAUXE9MTjN6ZiGr9GNH+qKfJtTo/P6aoUe4Yttyt6+VDTDAICSmFbZiunOakLlvFdwgimEr+JX/5jOR+YsTRVIYuevj321yUcQuoN2hvJdLSQCa+IS3PLMyWyBZH74echuwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final static String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final static String FORMAT = "JSON";
    //签名方式
    private final static String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final static String NOTIFY_URL = "http://h2630d7395.wicp.vip:37800/o2oo/frontend/productNotifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final static String RETURN_URL = "http://localhost:8080/o2oo/frontend/myrecord";

    /**
     * 获取网站支付表单
     * @param productPrice 价格
     * @param productName  商品名
     * @param body 描述
     * @param serialNumber 序列号
     * @return
     */
    public static String getAliPayFormText(BigDecimal productPrice, String productName, String body, String serialNumber) {
        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = serialNumber;
        //付款金额，必填
        String total_amount = String.valueOf(productPrice);
        //订单名称，必填
        String subject = productName;
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    /**
     * 验证支付宝异步通知的参数
     *
     * @param params
     * @return
     */
    public static boolean  verifySign(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(params,
                    ALIPAY_PUBLIC_KEY, CHARSET,
                    SIGN_TYPE);
        } catch (AlipayApiException e) {
            LOG.info("verify sign error:" + e);
        }
        return false;
    }

    public static Map<String, String> getParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<?, ?> requestParams = request.getParameterMap();
        for (Iterator<?> iter = requestParams.keySet().iterator(); iter
                .hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            LOG.info("alipay notify -->" + name + " = " + valueStr);
        }
        return params;
    }

}
